﻿
/// <summary>
/// CSharp扩展函数类
/// </summary>
using System.Security.Cryptography;
using System.Text;
public static class CSExtend
{
    /// <summary>
    /// 判断一个指定的字符串是null、空还是仅由空白字符组成
    /// 是[true]不是[false]
    /// </summary>
    /// <param name="str">指定的字符串</param>
    /// <returns></returns>
    public static bool IsNullOrWhiteSpace(this string str)
    {
        if (string.IsNullOrWhiteSpace(str))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 把一个对象转换为Json格式数据
    /// </summary>
    /// <param name="Object">需要转换的数据</param>
    /// <returns></returns>
    public static string ToJson(this object Object)
    {
        Newtonsoft.Json.Converters.IsoDateTimeConverter jsonsettingconvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
        jsonsettingconvert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        Newtonsoft.Json.JsonSerializerSettings jsonsetting = new Newtonsoft.Json.JsonSerializerSettings();
        jsonsetting.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        jsonsetting.Converters.Add(jsonsettingconvert);
        var jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(Object, jsonsetting);
        return jsonstring;
    }

    /// <summary>
    /// 将一个Json格式数据转换为一个指定类型的对象
    /// </summary>
    /// <typeparam name="T">指定的类型</typeparam>
    /// <param name="jsonString">Json格式字符串</param>
    /// <returns></returns>
    public static T ToObject<T>(this string jsonString)
    {
        if (string.IsNullOrEmpty(jsonString))
        {
            return default(T);
        }
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString);
    }

    /// <summary>
    /// 32位MD5加密
    /// </summary>
    /// <param name="str">待加密字符串</param>
    /// <returns></returns>
    public static string ToMD532(this string str)
    {
        string pwd = "";
        MD5 md5 = MD5.Create();
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
        for (int i = 0; i < s.Length; i++)
        {
            pwd = pwd + s[i].ToString("X");

        }
        return pwd;
    }
}

